import $ from 'jQuery';
let overAllIds = new Array();  //列表选中的全局数组
(function () {
    /**
     * 删除
     * @param params
     * @private
     */
    var _deleteDictionary = function (params) {
        IOT.getServerData(URI.SYSTEM.DICTIONARY.DELETE, params, (ret) => {
            IOT.hideOverlay();
            if (ret && ret.code === 200) {
                IOT.tips('删除成功！', 'success');
                layer.closeAll();
                M.Table.refresh.all();
            } else {
                IOT.tips(ret.message || '服务器请求失败，稍后再试！', 'error');
            }
        });
    };
    /**
     * 修改
     * @param params
     * @private
     */
    var _DictionaryModify =  function (params) {
        // $('#modifydicGroup').val(params.userId);
        // var type = params.dictgroupId == '故障类型' ? '1' : '2';
        var dictId =params.dictId;
        $('#modifydicGroup').val(params.dictgroupId);
        $('#modifydicName').val(params.dictName);
        $('#modifydicValue').val(params.dictValue);
        $('#modifydicText').val(params.dictNote);
        layer.open({
            type: 1,
            title: ['修改字典'],
            area: ['400px', '350px'],
            content:$('#modifyPara'),
            btn: ['确定', '取消'],
            yes: function(index, layero){
                layer.closeAll();
                IOT.showOverlay('保存中，请稍等...');
                // console.log("9999999999");
                $vue.modifydic.dictId=dictId;
                $vue.modifydic.dictgroupId=$('#modifydicGroup').val();
                $vue.modifydic.dictName=$('#modifydicName').val();
                $vue.modifydic.dictValue=$('#modifydicValue').val();
                $vue.modifydic.dictNote=$('#modifydicText').val();
                let param = $vue.$data.modifydic;
                console.log(param);
                IOT.getServerData(URI.SYSTEM.DICTIONARY.MODIFY ,param ,function (ret) {
                    IOT.hideOverlay();
                    if (ret && ret.code === 200) {
                        IOT.tips('保存成功！', 'success');
                        M.Table.refresh.all();
                        // M.Page.emitPrePage();
                    } else {
                        IOT.tips(ret.msg || '操作失败，请重试！', 'error', 1000, null);
                    }
                });
                return false;
            },
        });
    };
    let $vue = new Vue({
        el: '.main-hook',
        data: {
            // dicList:[{dictgroupId:"3b5fff8f323811e8b839000c29aedfd7",dictgroupName:'故障类型'},{dictgroupId:"3b5fff8f323811e8b839000c29aedfd8",dictgroupName:'控制器类型'}],
            dicList:[],
            newdic:{
                // dictgroupName:'',
                dictgroupId:'',
                dictName:'',
                dictValue:'',
                dictNote:'',
            },
            modifydic:{
                dictgroupId:'',
                // dictgroupName:'',
                dictName:'',
                dictValue:'',
                dictNote:'',
                dictId:''
            },
            boxs: {
                box1: {show: true, hook: '.box1-hook', lock: true, url: '', params: {}},
                box2: {show: false, hook: '.box2-hook', url: '', params: {}},
                box3: {show: false, hook: '.box3-hook', url: '', params: {}},
                box4: {show: false, hook: '.box4-hook', url: '', params: {}}
            },
        },
        created: function () {
            // M.Request.getRoleList(true, (roleList, ret) => {
            //     this.roleList = roleList;
            // });
            IOT.getServerData(URI.SYSTEM.DICTIONARY.GROUPLIST,'' , function (ret) {
                $vue.$data.dicList = ret.data;
            });

        },
        methods: {
            emitPage: function () {
                M.Page.load(this.boxs);
            },
            // 上一页
            prePage: function () {
                M.Page.prePage(this.boxs);
            },
            searchKey:function(){
                $('.search-hook').trigger('click');
            },
            // 触发刷新页(当前显示的页面)
            refreshPage: function () {
                M.Page.refreshPage(this.boxs);
            },
            //新增
            dicAdd:function(params){
                layer.open({
                    type: 1,
                    title: ['新增字典'],
                    area: ['400px', '350px'],
                    content:$('#addPara'),
                    btn: ['确定', '取消'],
                    yes: function(index, layero){
                        // console.log($('#newdicGroup').val());
                        $vue.newdic.dictgroupId=$('#newdicGroup').val();
                        $vue.newdic.dictName=$('#newdicName').val();
                        $vue.newdic.dictValue=$('#newdicValue').val();
                        $vue.newdic.dictNote=$('#newdicText').val();
                        // $('#newdicGroup').val('');
                        $('#newdicName').val('');
                        $('#newdicValue').val('');
                        $('#newdicText').val('');
                        layer.closeAll();
                        IOT.showOverlay('保存中，请稍等...');
                        let params = $vue.$data.newdic;
                        IOT.getServerData(URI.SYSTEM.DICTIONARY.ADD , params, function (ret) {
                            IOT.hideOverlay();
                            if (ret && ret.code === 200) {
                                IOT.tips('保存成功！', 'success');
                                M.Table.refresh.all();
                                // M.Page.emitPrePage();
                            } else {
                                IOT.tips(ret.msg || '操作失败，请重试！', 'error', 1000, null);
                            };
                        });
                        return false;
                    },
                });
            },
            //批量删除
            dicDelete:function(){
                let operateClear = overAllIds;
                console.log(overAllIds);
                // overAllIds=[];
                if(operateClear.length == 0){
                    layer.alert('请选择一条数据');
                    return false;
                }else {
                    layer.confirm('&nbsp;&nbsp; &nbsp;&nbsp;你确定要删除字典吗？', {
                        btn: ['确定','取消'] //按钮
                    }, function(){
                        let params = {};
                        params.dictId = operateClear.map(function (item,index,input) {
                            return item.dictId;
                        });
                        console.log("aaaaaaaaaa"+params);
                        IOT.showOverlay('删除中，请稍等...');
                        console.log(params);
                        _deleteDictionary(params);

                    }, function(){
                        //取消
                    });
                }
            },
        },
        mounted: function () {
            let thiz = this;
            this.$nextTick(() => {
                let tableHookName = '.dictionary-table-hook';
                let $accountBox = $('.dictionary-hook');
                //初始化时间插件
                // modal.initDate("startdate","enddate");
                var $form = $accountBox.find('.form-hook');
                // 查询
                $form.off('submit').on('submit', function () {
                    $(tableHookName).bootstrapTable('onCustomSearch');
                    return false;
                });
                var $tableHook = $accountBox.find(tableHookName).bootstrapTable({
                    scrollbar: 'dictionary-table-body',
                    striped: true, // 设置为 true 会有隔行变色效果
                    pagination: true, // true 显示分页
                    paginationDetail: true, // 分页详情
                    sidePagination: 'server', // 服务器端
                    method: 'post',
                    url: URI.SYSTEM.DICTIONARY.LIST,
                    debug: false,
                    cache: false,
                    pageNumber: 1,
                    pageSize: 10,
                    pageList: [10, 20, 50, 100],
                    smartDisplay:false,
                    // fixedColumns: true,
                    customButton: '',
                    customQueryParams: function (params) {
                        var formParams = $form.serializeJson();
                        var queryParams = $.extend({}, params, formParams);
                        //console.log(queryParams);
                        return queryParams;
                    },
                    onLoadSuccess: function (data) {
                        //console.log(JSON.stringify(data));
                    },
                    onLoadError: function (status, xhr) {
                    },
                    onCheckAll: function (rows) {

                    },
                    columns: [
                        {
                            field: 'checkStatus', checkbox: true, align: 'center', fixedLeft: true, width: 60,
                            formatter: function (i, row) {//每次加载checkbox时判断当前row的palletId是否已经存在全局里
                                for (var k = 0; k < overAllIds.length; k++) {
                                    //全局变量中含有id，则该复选框选中
                                    if (overAllIds[k].dictId == row.dictId) {
                                        return {
                                            checked: true //存在则选中
                                        }
                                    }
                                }
                            }
                        },
                        {
                            field: 'dictgroupName', title: '字典分组', align: 'center', fixedLeft: true,tips:true
                        },
                        {
                            field: 'dictName', title: '字典名称', align: 'center', fixedLeft: true,tips:true
                        },
                        {
                            field: 'dictValue', title: '字典值', align: 'center', fixedLeft: true,tips:true
                        },
                        {
                            field: 'dictNote', title: '备注信息', align: 'center', fixedLeft: true,tips:true
                        },
                        {
                            field: 'operate', title: '操作', align: 'center', fixedLeft: true, width: 180,
                            events: {
                                'click .modify-account': function (e, value, rowData, index) {
                                    _DictionaryModify(rowData);
                                    return false;
                                    // IOT.setSessionStore(URI.SYSTEM.ORGANIZE.PAGE, JSON.stringify(rowData));
                                    // return false;
                                },
                                'click .delete-account': function (e, value, row, index) {
                                    var rowdictId= {dictId:[row.dictId]};
                                    layer.confirm('&nbsp;&nbsp; &nbsp;&nbsp;你确定要删除字典吗？', {
                                        btn: ['确定','取消'] //按钮
                                    }, function(){
                                        let params = rowdictId;
                                        IOT.showOverlay('删除中，请稍等...');
                                        // console.log(params);
                                        _deleteDictionary(params);

                                    }, function(){
                                        //取消
                                    });
                                    return false;
                                },

                            },
                            formatter: function (value, row, index) {
                                let html = [];
                                if (M.Authority.checkAuthority('account-modify')) {
                                    html.push('<a class="modify-account operate">修改</a>');
                                }
                                if (!row.admin) {
                                    if (M.Authority.checkAuthority('account-delete')) {
                                        html.push('<a class="delete-account operate">删除</a>');
                                    }
                                }
                                return html.join('');
                            }
                        }

                    ]
                });
                //表格结束
                $('.dictionary-table-hook').on('uncheck.bs.table check.bs.table check-all.bs.table uncheck-all.bs.table', function (e, rows) {
                    var data = $.isArray(rows) ? rows : [rows]; //点击时获取选中的行或取消选中的行
                    examine(e.type, data); //保存到全局里
                });
                //权限——查看
                if (!M.Authority.checkAuthority('account-detail')&&!M.Authority.checkAuthority('account-modify')) {
                    $(tableHookName).bootstrapTable('hideColumn', 'operate');//隐藏列
                }
            });
        }
    });
})();

function examine(type,data){//操作选中的行
    if(type.indexOf('uncheck')==-1){
        $.each(data,function(i,v){//如果是选中则添加选中行的数据
            //添加时，判断一行或多行的palletId是否已经在数组里，不存则添加　
            overAllIds.indexOf(v.dictId) == -1 ? overAllIds.push(v) : -1;
        });
    }else{
        $.each(data,function(i,v){
            for(var k = overAllIds.length-1;k>=0;k--){
                if(overAllIds[k].dictId == v.dictId)
                    overAllIds.splice(k,1);//删除取消选中行
            }
        });
    }
}